<template>
  <div class="xyw_table">
    <el-table
      ref="tableData"
      :tree-props="ops"
      :data="tableData"
      size="medium"
      :header-cell-style="{ background: '#F3F3F5' }"
      :row-class-name="isCenter"
      :row-key="mergeOptions.mergeCols ? 'id' : ''"
      border
      @cell-click="cellClick"
      @row-click="rowClick"
      @row-dblclick="rowDBClick"
      @selection-change="handleSelectionChange"
    >
      <!-- 是否多选 -->
      <el-table-column
        v-if="mergeOptions.mutiSelect"
        type="selection"
        align="center"
      />
      <!-- 是否单选 -->
      <el-table-column
        v-if="mergeOptions.radioSelect"
        label="选择"
        width="55"
        align="center"
      >
        <template slot-scope="scope">
          <el-radio
            v-model="tableRadio"
            :label="scope.row"
            @change.native="clickChange(scope.row)"
            ><i></i
          ></el-radio>
        </template>
      </el-table-column>
      <!-- 是否展示序列号 -->
      <el-table-column
        v-if="mergeOptions.isindex"
        type="index"
        label="序号"
        :index="indexMethod"
        align="center"
        width="80"
      />
      <template v-for="(v, k) in headerData">
        <!-- 常规列数据  :show-overflow-tooltip="true" 超长hover显示  -->
        <el-table-column
          v-if="!v.type"
          :key="`v.label${k}`"
          :label="v.label"
          :width="v.width"
          :min-width="v.minWidth"
          :formatter="v.format"
          :prop="v.prop"
          align="center"
        >
          <template slot-scope="scope">
            <span :class="v.class ? v.class : ''">
              {{ scope.row[v.prop] }}
            </span>
          </template>
        </el-table-column>
        <!-- 图片数据列 -->
        <el-table-column
          v-if="v.type === 'image'"
          :key="`v.label${k}`"
          :label="v.label"
          :width="v.width"
          :min-width="v.minWidth"
          align="center"
        >
          <template slot-scope="scope" :formatter="v.format">
            <img
              class="cell-img"
              :src="scope.row[v.prop]"
              :formatter="v.format"
              alt=""
            />
          </template>
        </el-table-column>
        <!-- tag数据列 -->
        <el-table-column
          v-if="v.type === 'tag'"
          :key="`v.label${k}`"
          :label="v.label"
          :width="v.width"
          :min-width="v.minWidth"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="v.styleType">{{ scope.row[v.prop] }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="v.type === 'edit'" :key="`v.label${k}`" :label="v.label" :width="v.width" :min-width="v.minWidth" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-cascader v-model="scope.row.manageRange" collapse-tags :options="v.options" :props="{ multiple: true }"></el-cascader>
            </template>
            <span v-else>{{ scope.row.manageRangeStr }}</span>
          </template>
        </el-table-column> -->
        <!-- 处理type=btn，自定义按钮 -->
        <template v-if="v.type === 'btn'">
          <el-table-column label="操作" fixed="right" align="center">
            <template slot-scope="scope">
              <el-tooltip
                v-for="(item, index) in v.operationData"
                :key="`item.label${index}`"
                effect="dark"
                :content="item.label"
                placement="top"
              >
                <el-button size="mini" @click="btnClick(item, index, scope.row)"
                  ><i :class="item.icon"></i
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </template>
      </template>
    </el-table>
    <div v-if="mergeOptions.pagination" class="block">
      <!-- <el-pagination background :current-page="pagination.currentPage" :page-sizes="pagination.pageSizes" :page-size="pagination.pageSize" :layout="pagination.layout" :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> -->

      <!-- 分页组件 v-show="pagination.total>0" :total总条数 :page当前页，:limit每页多少条 pagination获取分页数据 -->
      <pagination
        :total="mergePagination.total"
        :page.sync="mergePagination.currentPage"
        :limit.sync="mergePagination.pageSize"
        @chagngePagination="getList"
      />
    </div>
  </div>
</template>

<script>
import pagination from "@/components/Pagination";
// import { TableConstants } from "@/config/constants/Index.js"; // 引入常量文件
// import tools from "@/utils/tools.js"; // 引入工具类
export default {
  name: "ELTableList",
  components: { pagination },
  props: {
    // 表格数据
    tableData: {
      type: Array,
      default: () => []
    },
    // 表格配置项
    options: {
      type: Object,
      default: () => {}
    },
    // 表格分页
    pagination: {
      type: Object,
      default: () => {}
    },
    ops: {
      type: Object,
      default: () => {}
    },
    // 表头数据
    headerData: {
      type: Array,
      default: data => {
        return (data = []);
      },
      formatters(row, column) {
        console.log(row, "format");
        console.log(column, "format");
      }
    }
  },
  data() {
    return {
      // tools,
      modifyWidthObj: null,
      isSubMenuName: false,
      tableRadio: null,
      defaultPagination: {
        currentPage: 1, // 当前页码
        pageSize: 100, // 每页多少条
        total: 0 // 多少条数据
      }
      // colList: TableConstants.ColumnSelf,
    };
  },
  computed: {
    // 计算是否传的有options有的话和默认值作合并
    mergeOptions() {
      // 默认table配置参数
      const defaultOptions = {
        mutiSelect: false, // boolean 是否多选
        radioSelect: false, // boolean 是否单选
        isindex: true, // boolean 是否展示序列号
        stripe: true, // boolean 斑马纹
        border: true, // boolean 纵向边框
        mergeCols: false, // boolean 合并列
        size: "small", // String  medium / small / mini  table尺寸
        fit: true, // 自动撑开
        pagination: true // 是否有分页
      };
      return Object.assign(defaultOptions, this.options || {});
    },
    // 计算是否传的有pagination有的话和默认值作合并
    mergePagination() {
      return Object.assign(this.defaultPagination, this.pagination || {});
    }
  },
  watch: {
    // tableData: function () {
    //   this.judgeBread();
    // },
  },
  created() {},
  mounted() {},
  methods: {
    isCenter({ row, column, rowIndex, columnIndex }) {
      if (
        this.options &&
        this.options.mergeCols &&
        (row.children !== undefined || Object.keys(row).length <= 3)
      ) {
        return "borderNo";
      }
    },
    cellClick(row, column, cell, event) {
      console.log("cellClick");
    },
    handleSelectionChange(val) {
      this.$emit("getSelectedData", val);
    },
    clickChange(val) {
      this.$emit("getRadiodData", val);
      console.log(val);
    },
    /**
     * 表格行点击事件  --单击
     */
    rowClick(row, column, cell, event) {
      this.$emit("rowClick", row, column, cell, event);
    },
    /**
     * 表格行点击事件  --双击
     */
    rowDBClick(row, column, cell, event) {
      this.$emit("rowDBClick", row, column, cell, event);
    },
    edit(index, row) {},
    /**
     * table 按钮点击事件  如编辑，删除等
     */
    btnClick(item, index, rowData) {
      console.log("my console rowDatarowData : ", rowData);
      this.$emit("btnClick", item, index, rowData);
    },
    // 序列号相关
    indexMethod(index) {
      return (
        (this.defaultPagination.currentPage - 1) *
          this.defaultPagination.pageSize +
        index +
        1
      );
    },
    getList(pageObj) {
      this.pagination.currentPage = pageObj.page;
      this.pagination.pageSize = pageObj.limit;
      this.$emit("getDataList");
    },
    // fo 自适应  获取单元格的宽度
    textSize(text, maxSize) {
      var span = document.createElement("div");
      var result = {};
      result.width = span.offsetWidth;
      result.height = span.offsetHeight;
      span.style.visibility = "hidden";
      span.style.fontSize = "14px";
      span.style.fontWeight = "500";
      span.style.fontFamily = "NotoSansSC-Regular";
      span.style.display = "inline-block";
      document.body.appendChild(span);
      if (typeof span.textContent !== "undefined") {
        span.textContent = text;
      } else {
        span.innerText = text;
      }
      result.width =
        parseFloat(window.getComputedStyle(span).width) - result.width;
      result.height =
        parseFloat(window.getComputedStyle(span).height) - result.height;
      document.body.removeChild(span);
      if (maxSize !== undefined && maxSize !== null) {
        return parseInt(result.width + 26) > maxSize
          ? parseInt(result.width + 30)
          : maxSize;
      }
      return parseInt(result.width + 30);
    },
    // 获取
    getTableObj(tableArr) {
      var obj = {};
      tableArr.forEach(function(element) {
        for (var key in element) {
          var imk = element[key];
          if (!obj[key]) {
            obj[key] = "";
          }
          if (
            Object.prototype.toString.call(element[key]) === "[object Object]"
          ) {
            imk =
              imk[key] === undefined
                ? imk.model && imk.model[key]
                  ? imk.model[key]
                  : ""
                : imk[key];
          }
          // if (window.textSize(imk) > obj[key]) {
          //   obj[key] = window.textSize(imk);
          // }
          if (imk === null) {
            imk = "";
          }
          if (typeof imk === "number") {
            imk = imk.toString();
          }
          if (
            typeof imk === "string" &&
            imk.length > (obj[key] ? obj[key].length : 0)
          ) {
            obj[key] = imk;
          }
        }
      });
      for (var i in obj) {
        obj[i] = this.textSize(obj[i]);
      }
      console.log(obj);
      return obj;
    },
    /**
     *  修改element table header的背景色
     */
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color:#E5E5E5; box-shadow:1px 1px 3px #333; border-bottom:1px solid #CDCDCD;";
      }
    }

    // judgeBread() {
    //   this.modifyWidthObj = this.getTableObj(this.tableData);
    //   // add 遍历constants中的列配置赋值
    //   // for (var item = 0; item < this.headerData.length; item++) {}
    //   // console.log(
    //   //   'my console  this.headerData: ',
    //   //   JSON.stringify(this.headerData)
    //   // )
    //   // modifyCols[0] = this.judgeBread(this.modifyWidthObj, )
    //   for (var item = 0; item < this.headerData.length; item++) {
    //     for (var obj in this.modifyWidthObj) {
    //       if (this.headerData[item].prop === obj) {
    //         let maxWidth = 0;
    //         if (this.modifyWidthObj[obj] > maxWidth) {
    //           maxWidth = this.modifyWidthObj[obj];
    //         }
    //         maxWidth = this.modifyWidthObj[obj];
    //         // 默认最小宽度小于计算出宽度
    //         if (this.headerData[item].minWidth < maxWidth) {
    //           this.headerData[item].minWidth = maxWidth;
    //         }
    //         if (
    //           this.colList.indexOf(this.headerData[item].prop.toString()) !== -1
    //         ) {
    //           // this.headerData[item].width = maxWidth
    //           if (this.headerData[item].width > maxWidth) {
    //             // 默认宽度大于计算出宽度
    //             if (
    //               this.headerData[item].minWidth &&
    //               maxWidth < this.headerData[item].minWidth
    //             ) {
    //               this.headerData[item].width = this.headerData[item].minWidth;
    //             } else {
    //               this.headerData[item].width = maxWidth;
    //             }
    //           }
    //         }
    //         // if (this.headerData[item].width > maxWidth) {
    //         //   this.headerData[item].width = maxWidth
    //         // }
    //       }
    //     }
    //   }
    // },
  }
};
</script>
<style lang="less" scoped>
.xyw_table {
  height: 100%;
  /deep/&.el-table--border,
  /deep/&.el-table--group {
    border: 1px solid #dcdfe6;
  }

  /deep/&.el-table--border {
    border-right: none;
    border-bottom: none;
  }

  /deep/&::before {
    background-color: #dcdfe6;
  }

  /deep/ th {
    background-color: #f3f3f3;
    text-align: center;
    color: #333333;
  }

  td,
  th.is-leaf {
    border-bottom: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
  }

  td {
    text-align: center;
    color: #666666;

    &.is-left {
      text-align: left;
    }
    .cell {
      .el-button--mini {
        border: none;
        font-size: 1.2rem;
        width: auto;
        min-width: auto;
        padding: 0;
        background-color: transparent;
      }
    }
  }
}
</style>
